package com.zq.mycloud.auth.advice;

import com.zq.mycloud.auth.exception.AuthException;
import com.zq.mycloud.core.consts.ErrorCodeConstant;
import com.zq.mycloud.core.respones.GeneralResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：zhang qiang
 * @package :com.zq.mycloud.auth.advice
 * @date ：Created in 2020/12/14 上午10:03
 * @description：自定义异常处理 TODO 后续根据不同的异常做不同处理
 * @modified By：
 * @version: $
 */
@RestControllerAdvice
@Slf4j
public class ControllerAdvice {

    /**
     * 处理自定义异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = AuthException.class)
    public GeneralResult myExceptionHandler(AuthException e, HttpServletRequest request) {
        StringBuilder sb = getLogString(request, e.getErrorCode(), e.getErrorInfo());
        log.error(sb.toString(), e);
        return new GeneralResult(e.getErrorCode(), e.getErrorInfo());
    }


    @ExceptionHandler(value = Exception.class)
    public GeneralResult exceptionHandle(Exception e, HttpServletRequest request)
    {
        GeneralResult result = new GeneralResult(ErrorCodeConstant.AUTH_INTERNAL_ERROR,e.getMessage());
        StringBuilder sb = toLogMsg(request, e, result);
        log.error("Internal Error, class={}", e.getClass());
        log.error(sb.toString(), e);
        return result;
    }


    /**
     * 生成打印信息
     *
     * @param request
     * @param e
     *
     * @return
     */
    private StringBuilder toLogMsg(HttpServletRequest request, Exception e, GeneralResult result)
    {
        return getRequestLogBuilder(request)
                .append(". Result:").append(result.toString())
                .append(". Exception msg:").append(e.getMessage());
    }


    private StringBuilder getLogString(HttpServletRequest request, String errorCode, String errorInfo) {
        return getRequestLogBuilder(request)
                .append(". Result = ")
                .append("errorCode:").append(errorCode)
                .append(", errorInfo:").append(errorInfo);
    }

    private StringBuilder getRequestLogBuilder(HttpServletRequest request) {
        return new StringBuilder().append("Failed to handle request:")
                .append(request.getMethod()).append(" ").append(request.getRequestURL());
    }
}
